package opensource.xinye.com.test11

import android.app.Activity
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ScrollView
import android.widget.TextView

class SocketHelper(val activity: Activity,onStartClick: () -> Unit =  {}) {


    val mPortEditText: EditText = activity.findViewById(R.id.port)
    val mStartButton: Button = activity.findViewById(R.id.start)
    val mScrollView: ScrollView = activity.findViewById(R.id.scrollView)
    val mLogTextView: TextView = activity.findViewById(R.id.logTextView)

    init {
        mStartButton.setOnClickListener {
            onStartClick()
        }
    }

    fun getPort(): Int{
        val text = mPortEditText.text.toString().trim()
        if(text.isEmpty()){
            return 0
        }
        return text.toInt()
    }

    fun logMessage(message: String){
        activity.runOnUiThread {
            mLogTextView.append(message)
            mLogTextView.append("\n")
            mScrollView.fullScroll(View.FOCUS_DOWN)
        }
    }

    open inner class Task(name: String,
               val onPreExecute: () -> Unit = {},
               val onBackgroundExecute: () -> Unit = {},
               val onPostExecute: () -> Unit = {}): Thread(name){

        private val mHandler = Handler(Looper.getMainLooper())

        override fun start() {
            mStartButton.isEnabled = false
            onPreExecute()
            super.start()
        }

        override fun run() {
            onBackgroundExecute()
            mHandler.post {
                mStartButton.isEnabled = true
                onPostExecute()
            }
            super.run()
        }
    }

}